package com.alex.common.tools;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.alex.common.Constants;

public class HostUtils {

	public final static String LOCAL_DOMAIN = "127.0.0.1";

	public final static Pattern IP_PATTERN = Pattern
			.compile("([0-9]{1,3}\\.){3}[0-9]{1,3}");

	private static boolean isnotIpAddr(String ipAddr) {
		return ((ipAddr == null) || (ipAddr.length() < 8));
	}

	public static String getRemoteAddr(HttpServletRequest request) {
		String ipAddr = request.getHeader("X-Forwarded-For");
		if (isnotIpAddr(ipAddr))
			ipAddr = request.getHeader("x-forwarded-for");
		if (isnotIpAddr(ipAddr))
			ipAddr = request.getHeader("HTTP_X_FORWARDED_FOR");
		if (isnotIpAddr(ipAddr))
			ipAddr = request.getRemoteAddr();
		return ipAddr;
	}

	/**
	 * e.g. 202.144.136.21:castmachine
	 * 
	 * @deprecated
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String getClientSign(HttpServletRequest request)
			throws IOException {
		String rhost = request.getRemoteHost();
		CookieUtils cu = new CookieUtils(request);
		Cookie ck = cu.get(Constants.COOKIE_NAME_CLIENTSIGN);
		return new StringBuilder(ck == null ? "" : ck.getValue()).append(":")
				.append(rhost).toString();
	}
}